from typing import Optional, List, Dict, Any
from pydantic import BaseModel, Field, validator

class ConversationMeta(BaseModel):
    """会话元数据模型"""
    inputs: Optional[Dict[str, Any]] = Field(None, description="会话初始输入变量")
    title: Optional[str] = Field(None, description="会话标题")
    description: Optional[str] = Field(None, description="会话描述")
    custom_data: Optional[Dict[str, Any]] = Field(None, description="自定义数据")

class ConversationCreateRequest(BaseModel):
    """创建会话请求模型"""
    user: str = Field(..., description="用户ID")
    auto_create: Optional[bool] = Field(True, description="是否自动创建，默认为True")
    conversation_id: Optional[str] = Field(None, description="指定会话ID，如果不自动创建则必须")
    meta: Optional[ConversationMeta] = Field(None, description="会话元数据")
    
    @validator('user')
    def user_not_empty(cls, v):
        """验证用户ID不为空"""
        if not v or not v.strip():
            raise ValueError("用户ID不能为空")
        return v
    
    @validator('conversation_id', always=True)
    def validate_conversation_id(cls, v, values):
        """验证会话ID在非自动创建时必须提供"""
        if 'auto_create' in values and not values['auto_create'] and not v:
            raise ValueError("当auto_create为False时，conversation_id必须提供")
        return v

class ConversationCreateResponse(BaseModel):
    """创建会话响应模型"""
    id: str = Field(..., description="会话ID")
    name: Optional[str] = Field(None, description="会话名称")
    inputs: Dict[str, Any] = Field({}, description="会话输入变量")
    status: str = Field("normal", description="会话状态")
    created_at: int = Field(..., description="创建时间戳")
    updated_at: Optional[int] = Field(None, description="更新时间戳")

class ConversationUpdateRequest(BaseModel):
    """更新会话请求模型"""
    user: str = Field(..., description="用户ID")
    name: Optional[str] = Field(None, description="会话名称")
    meta: Optional[ConversationMeta] = Field(None, description="会话元数据")

class ConversationItem(BaseModel):
    """会话项模型"""
    id: str = Field(..., description="会话ID")
    name: Optional[str] = Field(None, description="会话名称")
    inputs: Dict[str, Any] = Field({}, description="会话输入变量")
    status: str = Field(..., description="会话状态")
    introduction: Optional[str] = Field("", description="开场白")
    created_at: int = Field(..., description="创建时间戳")
    updated_at: Optional[int] = Field(None, description="更新时间戳")
    message_count: int = Field(0, description="消息数量")
    meta: Optional[ConversationMeta] = Field(None, description="会话元数据")

class ConversationListResponse(BaseModel):
    """会话列表响应模型"""
    data: List[ConversationItem] = Field(..., description="会话列表")
    has_more: bool = Field(..., description="是否有更多会话")
    limit: int = Field(..., description="每页数量限制")

class ConversationDetailResponse(ConversationItem):
    """会话详情响应模型，扩展自会话项"""
    pass

class ConversationDeleteResponse(BaseModel):
    """删除会话响应模型"""
    result: str = Field("success", description="操作结果")

class ConversationQueryParams(BaseModel):
    """会话查询参数模型"""
    user: str = Field(..., description="用户ID")
    last_id: Optional[str] = Field(None, description="当前页最后面一条记录的ID，默认null")
    limit: Optional[int] = Field(20, description="一次请求返回多少条记录，默认20条，最大100条，最小1条")
    sort_by: Optional[str] = Field("-updated_at", description="排序字段，默认-updated_at(按更新时间倒序排列)")
    
    @validator('limit')
    def limit_range(cls, v):
        """验证限制范围"""
        if v < 1 or v > 100:
            return 20  # 如果超出范围，默认为20
        return v

class MessageFile(BaseModel):
    """消息文件模型"""
    id: str = Field(..., description="文件ID")
    type: str = Field(..., description="文件类型，image 图片")
    url: str = Field(..., description="预览图片地址")
    belongs_to: str = Field(..., description="文件归属方，user 或 assistant")

class Feedback(BaseModel):
    """反馈信息模型"""
    rating: Optional[str] = Field(None, description="点赞 like / 点踩 dislike")

class RetrieverResource(BaseModel):
    """引用和归属分段模型"""
    position: int = Field(..., description="位置")
    dataset_id: str = Field(..., description="数据集ID")
    dataset_name: str = Field(..., description="数据集名称")
    document_id: str = Field(..., description="文档ID")
    document_name: str = Field(..., description="文档名称")
    segment_id: str = Field(..., description="分段ID")
    score: float = Field(..., description="相关度分数")
    content: str = Field(..., description="分段内容")

class ConversationMessage(BaseModel):
    """会话消息模型"""
    id: str = Field(..., description="消息ID")
    conversation_id: str = Field(..., description="会话ID")
    inputs: Dict[str, Any] = Field({}, description="用户输入参数")
    query: str = Field(..., description="用户输入/提问内容")
    answer: str = Field(..., description="回答消息内容")
    message_files: List[MessageFile] = Field([], description="消息文件")
    feedback: Optional[Feedback] = Field(None, description="反馈信息")
    retriever_resources: List[RetrieverResource] = Field([], description="引用和归属分段列表")
    created_at: int = Field(..., description="创建时间戳")
    
class ConversationMessageListResponse(BaseModel):
    """会话消息列表响应模型"""
    data: List[ConversationMessage] = Field(..., description="消息列表")
    has_more: bool = Field(..., description="是否存在下一页")
    limit: int = Field(..., description="返回条数，若传入超过系统限制，返回系统限制数量")

class ConversationRenameRequest(BaseModel):
    """会话重命名请求模型"""
    name: Optional[str] = Field(None, description="名称，若auto_generate为true时，该参数可不传")
    auto_generate: Optional[bool] = Field(False, description="自动生成标题，默认false")
    user: str = Field(..., description="用户标识，用于定义终端用户的身份，必须和发送消息接口传入user保持一致")
    
    @validator('user')
    def user_not_empty(cls, v):
        """验证用户ID不为空"""
        if not v or not v.strip():
            raise ValueError("用户ID不能为空")
        return v
